import base64
import os

from rest_framework import serializers
from rest_framework.response import Response

from django_redis import get_redis_connection

from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from users.models import User


class QQAuthUserSerializer(serializers.ModelSerializer):
    # 定义QQAuthUserView视图的序列化器
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    access_token = serializers.CharField(label='OpenID', write_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$', write_only=True)
    token = serializers.BooleanField(label='jwt token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'token', 'password', 'sms_code', 'access_token', 'mobile')
        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'min_length': 8,
                'max_length': 20,
                'write_only': True,
                'error_messages':
                    {
                        'min_length': '密码字符为8-20位',
                        'max_length': '密码字符为8-20位'
                    }
            }

        }

    def validate(self, attrs):
        # 检验access_token 是否正确
        access_token = attrs['access_token']
        # 校验openid是否能够解密
        openid = OAuthQQ.check_save_user_token(access_token)

        if not openid:
            return serializers.ValidationError('无效的openid')

        # 校验短信验证码是否正确
        sms_code = attrs['sms_code']
        mobile = attrs['mobile']

        # 获取redis对象
        res_conn = get_redis_connection('verify_codes')

        real_sms_code = res_conn.get('sms_code_%s' % mobile).decode()
        if not real_sms_code:
            return serializers.ValidationError('验证码不存在')

        if real_sms_code != sms_code:
            return serializers.ValidationError('验证码错误')
        # 校验密码是否正确
        password = attrs['password']
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = None
        else:
            # 手机已注册，需要校验密码是否正确
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
        # 将user添加到attrs中 ,创建对象的时候要用
        attrs['user'] = user
        # 将openid 添加到attrs中,创建对象的时候要用
        attrs['openid'] = openid
        return attrs

    # 如果用户不存在新增一个用户
    def create(self, validate_data):

        # 从参数中获取参数
        user = validate_data['user']
        mobile = validate_data['mobile']
        password = validate_data['password']

        if user is None:
            # 创建一个新的用户
            # 随机生成一个用户名
            username = base64.b64encode(os.urandom(16)).decode()
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile)

        # 在OauthQQUser中绑定用户的关系
        openid = validate_data['openid']

        OAuthQQUser.objects.create(
            openid=openid,
            user=user)
        # 由服务器生成一个jwt token字符串，保存用户的身份信息
        from rest_framework_jwt.settings import api_settings

        # 生成payload载荷
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)

        # 给user增加属性token，保存jwt token的内容
        user.token = token
        return user
